package com.powernode.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.powernode.constant.OrderStatusConstant;
import com.powernode.domain.Order;
import com.powernode.dto.PayOrderDto;
import com.powernode.feign.PayOrderFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RequestMapping
@RestController
@Api(tags = "支付管理")
public class PayController {

    @Value("${ali.my_private_key}")
    private String privateKey;

    @Value("${ali.ali_public_key}")
    private String publicKey;

    @Value("${ali.appId}")
    private String appId;

    @Autowired
    private PayOrderFeign payOrderFeign;

    @PostMapping("/p/order/pay")
    @ApiOperation("支付订单")
    public ResponseEntity<String> payOrder(@RequestBody Map<String, Object> map) throws AlipayApiException {

        AlipayClient alipayClient = new DefaultAlipayClient(
                "https://openapi.alipaydev.com/gateway.do",
                appId,
                privateKey,
                "json",
                "UTF-8",
                publicKey,
                "RSA2");
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        //扣款成功的通知地址
        //内网穿透
        request.setNotifyUrl("http://9qyx32.natappfree.cc/pay/notify");
        JSONObject bizContent = new JSONObject();
        //通过订单号获取到信息
        String orderNumber = map.get("orderNumber").toString();
        Order order = payOrderFeign.loadOrderByNo(orderNumber);
        bizContent.put("out_trade_no", orderNumber);
        bizContent.put("total_amount", order.getActualTotal());
        bizContent.put("subject", "测试商品");

        //// 商品明细信息，按需传入
        //JSONArray goodsDetail = new JSONArray();
        //JSONObject goods1 = new JSONObject();
        //goods1.put("goods_id", "goodsNo1");
        //goods1.put("goods_name", "子商品1");
        //goods1.put("quantity", 1);
        //goods1.put("price", 0.01);
        //goodsDetail.add(goods1);
        //bizContent.put("goods_detail", goodsDetail);

        //// 扩展信息，按需传入
        //JSONObject extendParams = new JSONObject();
        //extendParams.put("sys_service_provider_id", "2088511833207846");
        //bizContent.put("extend_params", extendParams);

        //// 结算信息，按需传入
        //JSONObject settleInfo = new JSONObject();
        //JSONArray settleDetailInfos = new JSONArray();
        //JSONObject settleDetail = new JSONObject();
        //settleDetail.put("trans_in_type", "defaultSettle");
        //settleDetail.put("amount", 0.01);
        //settleDetailInfos.add(settleDetail);
        //settleInfo.put("settle_detail_infos", settleDetailInfos);
        //bizContent.put("settle_info", settleInfo);

        //// 二级商户信息，按需传入
        //JSONObject subMerchant = new JSONObject();
        //subMerchant.put("merchant_id", "2088000603999128");
        //bizContent.put("sub_merchant", subMerchant);

        //// 业务参数信息，按需传入
        //JSONObject businessParams = new JSONObject();
        //businessParams.put("busi_params_key", "busiParamsValue");
        //bizContent.put("business_params", businessParams);

        //// 营销信息，按需传入
        //JSONObject promoParams = new JSONObject();
        //promoParams.put("promo_params_key", "promoParamsValue");
        //bizContent.put("promo_params", promoParams);

        request.setBizContent(bizContent.toString());
        AlipayTradePrecreateResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        String prodCode = request.getProdCode();
        return ResponseEntity.ok(prodCode);
    }

    //需要给此路径放行
    @PostMapping("/pay/notify")
    public String notify(Map<String, String> map) throws AlipayApiException {
        //回调的待验签字符串
        // String resultInfo = "buyer_id=208****42&total_amount=0.01&body=***试&trade_no=20190329**941025940236&notify_time=2019-03-29 19:42:04&subject=**电脑网站支付&sign_type=RSA2&charset=UTF-8&auth_app_id=201****222&notify_type=trade_status_sync&invoice_amount=0.01&out_trade_no=20190329ygyg45484544100003&trade_status=TRADE_SUCCESS&gmt_payment=2019-03-29 19:42:03&version=1.0&point_amount=0.00&sign=LDDUIGQmc+1qNtk3oyoAKVeMUKTngdX3ZjVeZOK0EjiPDJ/+Nk+0WSqcE6J7/5xb96Z/vP0yY3pVhZUiFVJ1G45/ys/HAleHh+EERZ1lkCkule1sSyaGFTKQGKx4uHpTyqIgRB1bouf19RPbSx1EkA0VkCarSy9G/OEG5Qmg8UdL2dRulMhlbOHS7tdMJJycDA8vOspOUMeQmk/H6IK9R2Kou5hN2T3KR1GWLYFK+z1jeZhQB3q52lZynO0OFjSzU4aQUBMW5QskQppBYd/ghtY/2YP+2H6YVGNgVmaheZMQ3PVTBALEV+8rZa91salH9DkKN2UCYGvNSNDT1VGCTQ==&gmt_create=2019-03-29 19:42:00&buyer_pay_amount=0.01&receipt_amount=0.01&fund_bill_list=[{\"amount\":\"0.01\",\"fundChannel\":\"PCREDIT\"}]&seller_id=208****5&app_id=2014100***22&notify_id=20190329002221942040**8";
        //编码格式
        String charset = "utf-8";
        //支付宝公钥
        String alipaypublicKey = publicKey;
        //签名方式
        String sign_type = "RSA2";
        //验签方法
        boolean signVerified = AlipaySignature.rsaCheckV1(map, alipaypublicKey, charset, sign_type);
        if (signVerified) {
            //获取订单号  上面传了订单号的
            String orderNo = map.get("out_trade_no");
            //定义一个类用于封装
            // TODO 验签成功后
            //成功后就 判断付款状态 通过状态选择后续业务逻辑
            String trade_status = map.get("trade_status");
            PayOrderDto orderDto = new PayOrderDto();
            orderDto.setOrderNo(orderNo);
            if ("WAIT_BUYER_PAY".equals(trade_status) || "TRADE_CLOSED".equals(trade_status)) {
                //未付款 或者 超时未支付
                //关闭订单 回退库存
                orderDto.setOrderStatus(OrderStatusConstant.WAIT_PAY);
                //订单关闭
                orderDto.setOrderType(2);
            } else {
                //支付成功
                //修改为代发货状态
                orderDto.setOrderStatus(OrderStatusConstant.WAIT_FAHUO);
            }
            payOrderFeign.updateOrder(orderDto);
            System.out.println("success");
            return "success";
        } else {
            System.out.println("fail");
            return "fail";
        }
    }

    @PostMapping("/pay/tradeStatus")
    boolean getOrderStatusFeign(@RequestBody String orderNo) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(
                "https://openapi.alipaydev.com/gateway.do",
                appId,
                privateKey,
                "json",
                "UTF-8",
                publicKey,
                "RSA2");
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +
                "  \"out_trade_no\":\"" + orderNo + "\"," +
                "  \"trade_no\":\"2014112611001004680 073956707\"," +
                "  \"query_options\":[" +
                "    \"trade_settle_info\"" +
                "  ]" +
                "}");
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            System.out.println("调用成功");
            //获取状态
            String tradeStatus = response.getTradeStatus();
            //已经支付返回true
            return "TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus);
        } else {
            System.out.println("调用失败");
        }
        return false;
    }
}
